package com.lalameow.loginbylogingate.network;

import com.lalameow.loginbylogingate.LoginByLoginGate;
import com.lalameow.loginbylogingate.config.ConfigManager;
import com.lalameow.loginbylogingate.network.handler.ClientHandler;
import com.lalameow.packet.BasePack;
import com.lalameow.packet.enumtype.PackType;
import com.lalameow.packet.packImpl.McServerConnectionPack;
import com.lalameow.packet.packImpl.VaildClientPack;
import com.lalameow.packet.packImpl.VaildPlayerPack;
import com.lalameow.packet.pojo.AuthenticateClient;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolver;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.bukkit.ChatColor;

import java.util.concurrent.CountDownLatch;

/**
 * Created with IntelliJ IDEA.
 * 创建人: 陈刚
 * 日期: 2018/5/11
 * 时间: 18:49
 * 功能：请进行修改
 */
public class LoginGateClient {
    public static  ClientState clientState=ClientState.INITIAL;
    private SocketChannel socketChannel;
    private ClientHandler clientHandler;

    public void initClient()  {
        LoginByLoginGate.plugin.getLogger().info(ChatColor.GREEN + "连接登录网关中....");
        EventLoopGroup eventLoopGroup=new NioEventLoopGroup();
        Bootstrap bootstrap=new Bootstrap();
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.SO_KEEPALIVE,true);
        bootstrap.group(eventLoopGroup);
        // bootstrap.remoteAddress("127.0.0.1", 7890);
        clientHandler=new ClientHandler();
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                socketChannel.pipeline().addLast(new IdleStateHandler(20,10,0));
                socketChannel.pipeline().addLast(new ObjectEncoder());
                ClassResolver classResolver=ClassResolvers.softCachingResolver(BasePack.class.getClassLoader());
                socketChannel.pipeline().addLast(new ObjectDecoder( classResolver));
                socketChannel.pipeline().addLast(clientHandler);
            }
        });
        try {
            ChannelFuture future = bootstrap.connect(ConfigManager.loginGateHost, ConfigManager.loginGatePort).sync();
            if (future.isSuccess()) {
                socketChannel = (SocketChannel) future.channel();
                LoginByLoginGate.plugin.getLogger().info(ChatColor.GREEN + "连接登录网关成功---------");
                //请求私钥
                requestPrivateKey();
                LoginGateClient.clientState=ClientState.START;
            }
        }catch (Exception e) {
            LoginByLoginGate.plugin.getLogger().info(ChatColor.RED + "连接登录网关失败！！！");
            LoginGateClient.clientState=ClientState.EXCEPTION;
            socketChannel=null;

        }
    }

    public CountDownLatch vaildPlayer(String playerName) throws InterruptedException {
        if(socketChannel!=null){
            CountDownLatch latch =new CountDownLatch(1);
            clientHandler.resetLatch(latch);
            BasePack basePack=new BasePack();
            basePack.setPackType(PackType.VAILDPLAYER);
            VaildPlayerPack vaildPlayerPack=new VaildPlayerPack();
            vaildPlayerPack.setPlayerName(playerName);
            basePack.setBodyContent(vaildPlayerPack.toJsonStr());
            socketChannel.writeAndFlush(basePack).sync();
            return latch;
        }
        return null;
    }
    public void vaildClient(AuthenticateClient authenticateClient) throws InterruptedException {
        if(socketChannel!=null){
            BasePack basePack=new BasePack();
            basePack.setPackType(PackType.VAILDCLIENT);
            VaildClientPack vaildClientPack=new VaildClientPack();
            vaildClientPack.setAuthenticateClient(authenticateClient);
            basePack.setBodyContent(vaildClientPack.toJsonStr());
            socketChannel.writeAndFlush(basePack);
        }
    }

    private void requestPrivateKey(){
        if(socketChannel!=null){
            BasePack basePack=new BasePack();
            basePack.setPackType(PackType.MCSERVERCONNECTION);
            McServerConnectionPack mcServerConnectionPack=new McServerConnectionPack();
            basePack.setBodyContent(mcServerConnectionPack.toJsonStr());
            socketChannel.writeAndFlush(basePack);
        }
    }
    public void disconnection(){
        if(socketChannel!=null){
            socketChannel.disconnect();
        }

    }
}
